package ru.spbu.math.android.cbrf.dataprovider.cbrf;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.res.Resources;
import android.util.Log;

import ru.spbu.math.android.cbrf.model.Category;
import ru.spbu.math.android.cbrf.model.Rate;
import ru.spbu.math.android.cbrf.model.RateType;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Class for parsing metal data from CBRF and put it in the List of Rate.
 * This class extends DefaultHandler
 * @author  Svetlana Zemlyanskaya
 */

//<Record Date="02.07.2001" Code="1">
//	<Buy>238,4</Buy> 
//	<Sell>253,54</Sell> 
//</Record>

public class MetalSaxHandler extends DefaultHandler {

	private final String LOG_TAG = "MetalSaxHandler";
	
    private final String BUY = "Buy";
    private final String RECORD = "Record";
    private final String DATE = "Date";
    private final String CODE = "Code";

    private final String AU = "1";
    private final String AG = "2";
    private final String PT = "3";
    private final String PD = "4";

    private Resources resources;
    private List<Rate> currList;

    private Rate currency;
    private StringBuilder builder;

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        builder.append(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        if (this.currency != null) {
            if (localName.equalsIgnoreCase(BUY)) {
            	String str = builder.toString().replace(",", ".").trim();
                currency.setValue(Double.parseDouble(str));
            } else if (localName.equalsIgnoreCase(RECORD)) {
                currList.add(currency);
            }

            builder.setLength(0);
        }
    }

    @Override
    public void startDocument() throws SAXException {
        currList = new ArrayList<Rate>();
        builder = new StringBuilder();
    }

    @Override
    public void startElement(String uri, String localName, String name,
                             Attributes attributes) throws SAXException {
        if (localName.equalsIgnoreCase(RECORD)) {
            this.currency = new Rate();
            String str = attributes.getValue(DATE);
            DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
            Date date = new Date();
            try {
                date = df.parse(str);
            } catch (ParseException e) {
                date = Calendar.getInstance().getTime();
                Log.e(LOG_TAG, "Parse Date Exception");
            }
            currency.setDate(date);
            
            String code = attributes.getValue(CODE);
            if (code.equals(AU)) {
                code = "AU";
            } else if (code.equals(AG)) {
                code = "AG";
            } else if (code.equals(PT)) {
                code = "PT";
            } else if (code.equals(PD)) {
                code = "PD";
            }

            RateTypeStore store = RateTypeStore.getInstance(resources);
            List<Category> categories = (List<Category>) store.getCategories();
            RateType type = null;
            for(Category category : categories){
            	List<RateType> rateTypes = (List<RateType>) store.getRateTypesByCategory(category);
            	for(RateType rateType : rateTypes){
            		if(code.equals(rateType.getSource().getCode())){
            			type = new RateType();
            			type = rateType;
            		}
            	}
            }
            currency.setResource(type);
        }
    }

    /**
	 * @return rate list from XML
	 */
    public List<Rate> getCurrency() {
        return currList;
    }
    
    /**
     * Set resources to the RateTypeStore
     * @param res
     */
    public void setResources(Resources res) {
    	resources = res;
    }
}

